import React, { useState, useEffect } from "react";
import { Table, Button, Input, Modal, Form, message } from 'antd';
import { connect } from 'react-redux';
import { ExclamationCircleFilled } from '@ant-design/icons';
import BrandManagementStyle from './BrandManagement.module.css'
import Store from './../../store/index';
import * as GoodsAttr from '../../store/actions/goods/action'
// 1.映射State到props:
function mapStateToProps(state) {
    return {
        data: state.GoodsAttr.GoodStr
    }
}
// 2. 映射方法到props:
function mapDispatchToProps(dispatch) {
    return {
        // sureReview: (obj) => { dispatch(warehousingAction.sureReviewBtn(obj)) },
        AttrEdit: (id, obj) => { dispatch(GoodsAttr.EditBtn(id, obj)) },
        AttrDel: (id) => { dispatch(GoodsAttr.DelBtn(id,)) },
        AttrsAdd: (obj) => { dispatch(GoodsAttr.addBtn(obj)) }
    }
}
const GoodSAttr = (props) => {
    const { AttrsAdd, AttrEdit, AttrDel } = props
    const { confirm } = Modal;
    // 打开关闭模态框
    const [open, setOpen] = useState(false);
    const [open2, setOpen2] = useState(false);
    // 添加编辑标题titleMap
    const [titleMap, setTitleMap] = useState()
    // 模态框确定按钮的操作
    const [MType, setMType] = useState()
    // 添加
    const [addForm] = Form.useForm()
    // 修改
    const [editForm] = Form.useForm()
    const [columns, setColumns] = useState([
        {
            title: '属性名称', dataIndex: 'name', key: 'name',
        },
        {
            title: '属性值', dataIndex: 'AttrV', key: 'AttrV',
        },
        {
            title: '排序', dataIndex: 'sort', key: 'sort',
            sorter: (a, b) => a.sort - b.sort,
        },
        {
            title: '操作', dataIndex: '',
            render: (text) => (
                <div>
                    <Button type="link" onClick={() => onHandleEdit(text)}>编辑</Button>
                    <Button type="link" onClick={() => del(text)}>删除</Button>
                </div>
            )
        },

    ]);
    const [data, setData] = useState(Store.getState().GoodsAttr.GoodStr);
    useEffect(() => {
        setData(Store.getState().GoodsAttr.GoodStr)

    }, [data])

    // 删除函数
    const del = (obj) => {
        console.log(obj);
        confirm({
            title: '你确定删除当前行吗',
            icon: <ExclamationCircleFilled />,
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                AttrDel(obj.id)
                setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodStr)))
                message.success('删除成功')

            },
            onCancel() {
                console.log('Cancel');
                message.error('删除失败')
            },
        });
    }
    // 新增函数
    const BrandAdd = () => {
        addForm.setFieldsValue({
            "id": data.length + 1
        })
        setOpen(true);
        setTitleMap('新增属性')
    }
    // 添加确认按钮
    const handleOk = (values) => {
        console.log('Success:', values);
        setOpen(false);
        AttrsAdd(values)
        message.success('操作成功')
        setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodStr)))
        addForm.resetFields()

    };

    // 添加模态框取消按钮
    const onCannel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
    };
    // 编辑确认按钮
    const handleOk2 = (values) => {
        console.log('Success:', values);
        AttrEdit(values.id, { ...values })
        setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodStr)))
        setOpen2(false);
        editForm.resetFields()
        message.success('操作成功')
    };

    // 模态框取消按钮
    const onCannel2 = () => {
        console.log('Clicked cancel button');
        setOpen2(false);
    };


    // 编辑函数
    const onHandleEdit = (obj) => {
        let showData = {}
        setTitleMap('编辑属性')
        data.forEach(el => {
            if (el.id === obj.id) {
                showData = JSON.parse(JSON.stringify(el))
            }
        });
        editForm.setFieldsValue(showData)
        setOpen2(true)

    }

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const onDataChange = (sorter) => {
        console.log('params', sorter);
    };
    return (
        <>
            <div className={BrandManagementStyle.title}>
                <div >
                    <Button type="primary" className={BrandManagementStyle.titleLeft} onClick={() => BrandAdd()}>新建属性</Button>
                </div>
            </div>
            <Table columns={columns} rowKey={record => record.id} dataSource={data} onChange={onDataChange} />
            <Modal
                title={titleMap}
                open={open}
                closable={false}
                footer={null}
            >
                <Form name="basic" form={addForm} labelCol={{ span: 8, }} wrapperCol={{ span: 16, }} initialValues={{ remember: true, }} onFinish={handleOk} onFinishFailed={onFinishFailed} autoComplete="off"
                >
                    <Form.Item name="id" hidden                    >
                        <Input />
                    </Form.Item>
                    <Form.Item label="属性名称" name="name" placeholder='请输入'
                        rules={[
                            {
                                required: true,
                                message: '必须输入名称',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>

                    <Form.Item label="属性值" name="AttrV"                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item label="排序" name="sort"                  >
                        <Input placeholder='请输入数' />
                    </Form.Item>

                    <Form.Item >
                        <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                                确认
                            </Button>
                            <Button type="primary" onClick={onCannel}>
                                取消
                            </Button>
                        </div>
                    </Form.Item>
                </Form>
            </Modal>
            {/* 编辑 */}
            <Modal
                title={titleMap}
                open={open2}
                closable={false}
                footer={null}
            >
                <Form
                    name="basic" labelCol={{ span: 8, }}
                    wrapperCol={{ span: 16, }}
                    initialValues={{ remember: true, }}
                    onFinish={handleOk2} onFinishFailed={onFinishFailed} autoComplete="off" form={editForm}
                >
                    <Form.Item hidden name="id">
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="属性名称" name="name" placeholder='请输入' rules={[
                            {
                                required: true,
                                message: '11',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>

                    <Form.Item label="属性值" name="AttrV"                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        label="排序" name="sort"
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item >
                        <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                                确认
                            </Button>
                            <Button type="primary" onClick={onCannel2}>
                                取消
                            </Button>
                        </div>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}
export default connect(mapStateToProps, mapDispatchToProps)(GoodSAttr)